package com.mrzhou.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Java原生Socket Server端:
 *  IO模型: BIO
 *      特点: 同步, 阻塞式, 当服务器收到客户端请求时, 则新开一个线程处理当前请求
 *      缺点: 耗费服务资源极大, 线程重复利用率低, 不能承受高并发
 *      优化: 使用线程池+等待队列, 避免开启过多线程
 */
public class SocketServer {

    public static void main(String[] args) {
        final int DEFAULT_PORT = 8888; // socket服务器端默认端口号

        try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)){
            while (true) { // 保证服务端一直运行
                Socket socket = serverSocket.accept(); // 阻塞式监听, 如果一直没有客户端请求则停留在此处
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 读取消息
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // 写消息
                String msg ;
                while ((msg = reader.readLine()) != null) {
                    System.out.println("Client[" + socket.getPort() + "]:" + msg);
                    // 写入服务器要发送的消息
                    writer.write("Server:" + msg + "\n");
                    writer.flush();
                    if (msg.equals("quit")) {
                        System.out.println("Client[" + socket.getPort() + "]:Offline");
                        break;
                    }
                }

            }
        } catch (IOException e) {

        }


    }

}
